import { ExclamationCircleFilled } from '@ant-design/icons'
import { Modal } from 'antd'
import { useContext, useEffect, useRef, useState } from 'react'
import AceEditor from 'react-ace'
import { useTranslation } from 'react-i18next'
import { Button } from '../../../components/bs-ui/button'
import { alertContext } from '../../../contexts/alertContext'
import { checkSysConfigApi, getSysConfigApi, setSysConfigApi } from '../../../controllers/API/user'
import { captureAndAlertRequestErrorHoc } from '../../../controllers/request'

export default function Config() {
  const { setErrorData, setSuccessData } = useContext(alertContext)
  const [config, setConfig] = useState('')

  const { t } = useTranslation()

  useEffect(() => {
    captureAndAlertRequestErrorHoc(
      getSysConfigApi().then(jsonstr => {
        setConfig(jsonstr)
        codeRef.current = jsonstr
      })
    )
  }, [])

  const handleSave = () => {
    if (validataRef.current.length) {
      return setErrorData({
        title: `yaml${t('formatError')}`,
        list: validataRef.current.map(el => el.text)
      })
    }
    checkSysConfigApi({ data: codeRef.current })
      .then((res: any) => {
        console.log(res)
        if (res?.check_faild) {
          Modal.confirm({
            title: '提示',
            icon: <ExclamationCircleFilled />,
            content: res.msg,
            cancelText: '取消',
            okText: '确定',
            autoFocusButton: null,
            centered: true,
            destroyOnClose: true,
            onOk() {
              captureAndAlertRequestErrorHoc(
                setSysConfigApi({ data: codeRef.current }).then(res => {
                  setSuccessData({ title: t('success') })
                  setConfig(codeRef.current)
                })
              )
            }
          })
        } else {
          captureAndAlertRequestErrorHoc(
            setSysConfigApi({ data: codeRef.current }).then(res => {
              setSuccessData({ title: t('success') })
              setConfig(codeRef.current)
            })
          )
        }
      })
      .catch(err => {
        console.log('err', err)
      })
  }

  const codeRef = useRef('')
  const validataRef = useRef([])
  return (
    <div className=" mx-auto max-w-[80%]">
      <p className="mb-2 mt-8 font-bold">{t('system.parameterConfig')}</p>
      <AceEditor
        value={config || ''}
        mode="yaml"
        theme={'twilight'}
        highlightActiveLine={true}
        showPrintMargin={false}
        fontSize={14}
        showGutter
        enableLiveAutocompletion
        name="CodeEditor"
        onChange={value => (codeRef.current = value)}
        onValidate={e => (validataRef.current = e)}
        className="h-[70vh] w-full rounded-lg border-[1px] border-border custom-scroll"
      />
      <div className="mt-8 flex justify-center">
        <Button className=" h-10 w-[120px] px-24" onClick={handleSave}>
          {t('save')}
        </Button>
      </div>
    </div>
  )
}
